import { defineStore } from "pinia";

export const useUserStore = defineStore("user", () => {
  const userInfo = ref({
    id: "",
    avatarUrl: "",
    nickName: "",
  });

  /* getter */
  const isLogin = computed(() => !!userInfo.value.id);
  const userName = computed(() => userInfo.value.nickName || "未知用户");
  const userAvatar = computed(
    () => userInfo.value.avatarUrl || "@/static/images/user.png"
  );
  /* action  */
  //   设置用户信息
  function setUserInfo(data) {
    userInfo.value = { ...userInfo.value, ...data };
  }

  // 清空用户信息
  function clearUserInfo() {
    userInfo.value = {
      id: "",
      avatarUrl: "",
      nickName: "",
    };
  }
  // 更新用户头像
  function updateAvatar(url) {
    userInfo.value.avatarUrl = url;
  }

  return {
    userInfo,

    isLogin,
    userName,
    userAvatar,

    setUserInfo,
    clearUserInfo,
    updateAvatar,
  };
});
